import React, { useRef, useState, useEffect } from 'react'
import { PageContainer, ProTable, ActionType, ProDescriptionsItemProps, FooterToolbar } from '@ant-design/pro-components'
import { Button, Divider, message} from 'antd';
import { nanoid } from 'nanoid';
import { queryArticleList, queryCategoryList, addArticle, editArticle} from '@/services/article';

import CreateForm from './components/CreateForm';

const ArticleList: React.FC = () => {
    const tableRef = useRef<ActionType>();

    //表单的选择数据
    const [selectedRowsState, setSelectedRows] = useState<API.UserInfo[]>([]);

    //分类相关数据
    const [categoryList, setCategoryList] = useState({})
    const fetchCategoryList = async () => {
        const { data } = await queryCategoryList()
        setCategoryList(data?.list || {})
    }

    //表单的列数据
    const columns: ProDescriptionsItemProps[] = [
        {
            title: "文章标题", dataIndex: "title", tooltip: '搜索标题关键字', formItemProps: {
                rules: [{ required: true, message: '名称为必填项' }]
            }
        },
        { title: '内容', dataIndex: 'content', valueType: 'text', formItemProps: {
                rules: [{ required: true, message: '内容必须填写' }]
            }
        },
        {
            title: '分类', dataIndex: 'category', hideInForm: false, valueEnum: categoryList,
            formItemProps: {
                rules: [{ required: true, message: '分类必须选择' }]
            }
        },
        {
            title: "操作", dataIndex: 'option', valueType: 'option', render: (_, record) => (
                <>
                    <a onClick={() => handleEditClick(record)}>编辑</a>
                    <Divider type="vertical" />
                    <a onClick={() => { }}>删除</a>
                </>
            )
        }
    ]
    
    //添加表单相关
    const [isEdit, setIsEdit] = useState<boolean>(false);
    const [createModalVisible, handleModalVisible] = useState<boolean>(false);
    
    //编辑相关
    const [defaultData, setDefaultData] = useState<{id:string} | any>({});
    const handleEditClick = (record:any)=>{
        setDefaultData(record)
        setIsEdit(true)
        handleModalVisible(true)
    }
    const handleCreateSubmit = async (value:any) =>{
        const hide = message.loading('进行中...');
        try {
          if(isEdit){
            await editArticle(defaultData.id,{...value})
          }else{
            await addArticle({ ...value, id:nanoid()});
          }
          hide();
          message.success('操作成功');
          handleModalVisible(false)
          if (tableRef.current) {
            tableRef.current.reload();
          }
          return true;
        } catch (error) {
          hide();
          message.error('添加失败请重试！');
          return false;
        }
    }


    //生命周期钩子
    useEffect(() => {
        fetchCategoryList()
    }, [])

    return (
        <PageContainer header={{ title: '文章列表' }}>
            <ProTable
                actionRef={tableRef}
                rowKey="id"
                search={{ labelWidth: 120 }}
                toolBarRender={() => [<Button key="1" type="primary" onClick={()=>{handleModalVisible(true);setIsEdit(false)}}>新建</Button>]}
                request={async (params, sorter, filter) => {
                    const { data, success } = await queryArticleList({
                        ...params,
                        // FIXME: remove @ts-ignore
                        // @ts-ignore
                        sorter,
                        filter,
                    })

                    return {
                        data: data?.list || [],
                        success,
                    }
                }}
                columns={columns}
                rowSelection={{
                    onChange: (_, selectedRows) => setSelectedRows(selectedRows),
                }}
            />

            {/* 工具条 */}
            {
                selectedRowsState?.length > 0 && (
                    <FooterToolbar
                        extra={
                            <div>
                                已选择{' '}
                                <a style={{ fontWeight: 600 }}>{selectedRowsState.length}</a>{' '}
                                项&nbsp;&nbsp;
                            </div>
                        }
                    >
                        <Button>批量删除</Button>
                        <Button type="primary">批量审核</Button>
                    </FooterToolbar>
                )
            }

            {/* 添加 修改弹窗 */}
            <CreateForm 
                columns={columns} 
                modelVisible={createModalVisible} 
                isEdit={isEdit}
                onCancel={()=>handleModalVisible(false)} 
                onSubmit={value=>handleCreateSubmit(value)}
                defaultData={isEdit?defaultData:{}}
            />
        </PageContainer>
    )
}

export default ArticleList